﻿using System;
using System.Data;
using DevExpress.Web.ASPxGridView;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using NguyenHoa.Web.App_Code;

namespace NguyenHoa.Web.Admin
{
  public partial class ContactPage : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.SystemSetting;
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      InitPage();
      if (!IsCallback && !IsPostBack)
      {
        LoadPage();
        LoadAddress();
        LoadHotline();
        LoadOnlineSupport();
        LoadMap();
      }

      if (gvHotline.IsCallback)
      {
        LoadHotline();
      }

      if (gvOnline.IsCallback)
      {
        LoadOnlineSupport();
      }

      if (gvMap.IsCallback)
      {
        LoadMap();
      }
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "Save")
      {
        e.Result = SaveAddress();
      }
      else if (para[0] == "ChangeLang")
      {
        e.Result = "HTML|" + GetContactHtml();
      }
    }

    #region Hotline Grid
    protected void gvHotline_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      //string[] para = e.Parameters.Split('|');
      //if (para[0] == "Load")
      //{
      //  LoadHotline();
      //}
    }

    protected void gvHotline_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvHotline_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteHotline(id);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadHotline();
    }

    protected void gvHotline_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string phone = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      int id = 0;

      if (string.IsNullOrEmpty(phone))
      {
        m_innerError = String.Format(Resources.Messages.ERR0007, Resources.Strings.Phone.ToUpper());
      }
      else
        m_innerError = SaveHotline(id, phone);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadHotline();
    }

    protected void gvHotline_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      string phone = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      if (string.IsNullOrEmpty(phone))
      {
        m_innerError = Resources.Messages.ERR0008;
        m_innerError += "<BR> + " + Resources.Strings.Hotline;
      }
      else
        m_innerError = SaveHotline(id, phone);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadHotline();
    }
    #endregion

    #region Online Grid
    protected void gvOnline_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {

    }

    protected void gvOnline_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvOnline_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteOnline(id);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadOnlineSupport();
    }

    protected void gvOnline_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string nick = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      string type = (e.NewValues["Type"] != null) ? e.NewValues["Type"].ToString() : string.Empty;
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;
      string activity = (e.NewValues["Activity"] != null) ? e.NewValues["Activity"].ToString() : string.Empty;
      int id = 0;

      if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(nick))
      {
        m_innerError = String.Format(Resources.Messages.ERR0007, "Chatting Nick");
        goto FINISH;
      }
      m_innerError = SaveOnline(id, nick, type, activity, name);

    FINISH:
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadOnlineSupport();
    }

    protected void gvOnline_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      string nick = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      string type = (e.NewValues["Type"] != null) ? e.NewValues["Type"].ToString() : string.Empty;
      string name = (e.NewValues["Name"] != null) ? e.NewValues["Name"].ToString() : string.Empty;
      string activity = (e.NewValues["Activity"] != null) ? e.NewValues["Activity"].ToString() : string.Empty;
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(nick))
      {
        m_innerError = String.Format(Resources.Messages.ERR0007, "Chatting Nick");
        goto FINISH;
      }
      m_innerError = SaveOnline(id, nick, type, activity, name);

    FINISH:
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadOnlineSupport();
    }

    protected void gvOnline_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
    {
      if (!gvOnline.IsNewRowEditing) return;
      if (e.Column.FieldName == "Type")
      {
        e.Editor.Value = OnlineType.Yahoo;
      }
      else if (e.Column.FieldName == "Activity")
      {
        e.Editor.Value = OnlineType.Contact;
      }
    }
    #endregion

    #region Map
    protected void gvMap_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvMap_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {

    }

    protected void gvMap_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string url = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      int id = 0;
      int language = (e.NewValues["LanguageId"] != null) ? Convert.ToInt32(e.NewValues["LanguageId"]) : CurrentLanguage.Id;

      if (string.IsNullOrEmpty(url))
      {
        m_innerError = String.Format(Resources.Messages.ERR0007, Resources.Strings.ReferenceLink.ToUpper());
      }
      else
        m_innerError = SaveMap(id, url);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadMap();
    }

    protected void gvMap_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      string url = (e.NewValues["Value"] != null) ? e.NewValues["Value"].ToString() : string.Empty;
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      if (string.IsNullOrEmpty(url))
      {
        m_innerError = Resources.Messages.ERR0008;
        m_innerError += "<BR> + " + Resources.Strings.ReferenceLink;
      }
      else
        m_innerError = SaveMap(id, url);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadMap();
    }

    protected void gvMap_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out id);
      m_innerError = DeleteMap(id);
      ASPxGridView grid = sender as ASPxGridView;
      e.Cancel = true;
      grid.CancelEdit();
      LoadMap();
    }
    #endregion
    #endregion

    #region Methods
    private void InitPage()
    {
      xdsLanguage.DataFile = xdsActivity.DataFile = xdsType.DataFile = XmlStatusFile;
    }

    private void LoadPage()
    {
      cbxLanguage.Value = CurrentLanguage.Id;
      cbxType.Value = ContactType.ContactInfo;
    }

    private void LoadAddress()
    {
      htmlEditor.Html = GetContactHtml();
    }

    private string GetContactHtml()
    {
      string html = string.Empty, type = cbxType.Value.ToString();
      int language = CurrentLanguage.Id;
      if (cbxLanguage.Value != null)
        language = Convert.ToInt32(cbxLanguage.Value);
      TList<ContactInfo> add = new ContactInfoService().GetByTypeAndLanguage(type, language, true);
      if (add != null && add.Count > 0 && add[0] != null)
      {
        html = add[0].Value;
      }
      return html;
    }

    private string SaveAddress()
    {
      try
      {
        int language = CurrentLanguage.Id;
        if (cbxLanguage.Value != null)
          language = Convert.ToInt32(cbxLanguage.Value);
        string type = cbxType.Value.ToString();
        ContactInfoService service = new ContactInfoService();
        TList<ContactInfo> add = service.GetByTypeAndLanguage(type, language, true);
        ContactInfo info;
        if (add != null && add.Count > 0 && add[0] != null)
        {
          info = add[0];
        }
        else
        {
          info = new ContactInfo();
          info.Type = type;
          info.LanguageId = language;
          info.Name = "Company Contact";
          info.IsShow = true;
        }
        info.Value = htmlEditor.Html;
        service.Save(info);
        switch (type)
        {
          case ContactType.CompanyAddress:
            //GlobalCache.Instance.ContactAddress = null;
            break;
          case ContactType.ContactInfo:
            //GlobalCache.Instance.ContactInfo = null;
            break;
        }
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Save Adrress", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    #region Hotline
    private void LoadHotline()
    {
      gvHotline.DataSource = new ContactInfoService().GetByTypeAndLanguage(ContactType.Hotline, null, true);
      gvHotline.DataBind();
    }

    private string DeleteHotline(int id)
    {
      try
      {
        new ContactInfoService().Delete(id);
        //GlobalCache.Instance.SetHotLine(null);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Delete hotline", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string SaveHotline(int id, string phone)
    {
      try
      {
        ContactInfoService service = new ContactInfoService();
        ContactInfo hotline = null;
        if (id > 0)
        {
          hotline = service.GetById(id);
          if (hotline == null)
            return Resources.Messages.ERR0003;
        }
        else
        {
          hotline = new ContactInfo();
          hotline.Type = ContactType.Hotline;
          hotline.IsShow = true;
        }

        hotline.Value = phone;
        hotline.LanguageId = CurrentLanguage.Id;
        service.Save(hotline);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Save hotline", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
    #endregion

    #region OnlineSupport
    private void LoadOnlineSupport()
    {
      DataTable tbl = new DataTable("Online");
      tbl.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32")));
      tbl.Columns.Add(new DataColumn("Value", Type.GetType("System.String")));
      tbl.Columns.Add(new DataColumn("Type", Type.GetType("System.String")));
      tbl.Columns.Add(new DataColumn("Activity", Type.GetType("System.String")));
      tbl.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));

      TList<ContactInfo> contactList = new ContactInfoService().GetByTypeAndLanguage(null, null, null);
      foreach (ContactInfo contact in contactList)
      {
        string type = contact.Type;
        if (type == ContactType.SkypeContact || type == ContactType.SkypeSale ||
          type == ContactType.YahooContact || type == ContactType.YahooSale)
        {
          tbl.Rows.Add(new object[] { contact.Id, contact.Value, type[1], type[0], contact.Name });
        }
      }
      gvOnline.DataSource = tbl;
      gvOnline.DataBind();
    }

    private string DeleteOnline(int id)
    {
      try
      {
        new ContactInfoService().Delete(id);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Delete online", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string SaveOnline(int id, string value, string type, string activity, string name)
    {
      try
      {
        ContactInfoService service = new ContactInfoService();
        Domains.ContactInfo contact = null;
        if (id > 0)
        {
          contact = service.GetById(id);
          if (contact == null)
            return Resources.Messages.ERR0003;
        }
        else
        {
          contact = new Domains.ContactInfo();
          contact.IsShow = true;
        }
        contact.Type = activity + type;
        contact.Value = value;
        contact.Name = name;
        service.Save(contact);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Save online", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
    #endregion

    #region Map
    private void LoadMap()
    {
      gvMap.DataSource = new ContactInfoService().GetByTypeAndLanguage(ContactType.ViewMap, null, true);
      gvMap.DataBind();
    }

    private string DeleteMap(int id)
    {
      try
      {
        new ContactInfoService().Delete(id);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Delete map", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string SaveMap(int id, string url)
    {
      try
      {
        ContactInfoService service = new ContactInfoService();
        ContactInfo map = null;
        if (id > 0)
        {
          map = service.GetById(id);
          if (map == null)
            return Resources.Messages.ERR0003;
        }
        else
        {
          map = new ContactInfo();
          map.Type = ContactType.ViewMap;
          map.IsShow = true;
        }

        map.Value = url;
        map.LanguageId = CurrentLanguage.Id;
        service.Save(map);
      }
      catch (Exception ex)
      {
        WriteLog("ContactInfo.aspx::Save map", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
    #endregion
    #endregion
  }
}